gameInfo = {
    roomId: null,
    thisUserId: null,
    thatUserId: null,
    isWhite: true,
}

//////////////////////////////////////////////////
// 设定界面显示相关操作
//////////////////////////////////////////////////

function setScreenText(me) {
    let screen = document.querySelector('#screen');
    if (me) {
        screen.innerHTML = "轮到你落子了!";
    } else {
        screen.innerHTML = "轮到对方落子了!";
    }
}

//////////////////////////////////////////////////
// 初始化 websocket
//////////////////////////////////////////////////
// TODO
let websocketUrl = "ws://" + location.host + "/game";
let websocket = new WebSocket(websocketUrl);
websocket.onopen = function() {
    console.log("游戏房间连接成功！");
}
websocket.onclose = function() {
    console.log("连接已断开！");
    
}
websocket.onerror = function() {
    console.log("连接出现异常");
    
}
// 窗口关闭，断开连接
window.onbeforeunload = function() {
    websocket.close();
}

// 处理服务器返回的响应数据
websocket.onmessage = function(e) {
    let resp = JSON.parse(e.data);
    if (resp.status == 'matchFail') {
        location.replace("/game_hall.html");
    } else if (resp.status == "unlogin") {
        location.replace("/login.html");
    } else if (resp.status == "repeatConnection") {
        alert("当前检测到多开！请使用其他账号登录！")
        ocation.replace("/login.html");
    } else if (resp.status == "gameReady") {
        // 服务器初始化完成，将 gameinfo
        console.log(resp.data);
        let roomInfo = resp.data;
        gameInfo.roomId = roomInfo.roomId;
        gameInfo.thisUserId = roomInfo.userId;
        gameInfo.thatUserId = roomInfo.rivalId;
        gameInfo.isWhite = (roomInfo.userId == roomInfo.whiteUser);
        console.log(gameInfo);
        // 初始化棋盘
        initGame();
        // 设置显示区域内容
        setScreenText(gameInfo.isWhite);
    } else {
        alert("接收到非法响应: " + resp.errorMessage)
    }
}


//////////////////////////////////////////////////
// 初始化一局游戏
//////////////////////////////////////////////////
function initGame() {
    // 是我下还是对方下. 根据服务器分配的先后手情况决定
    let me = gameInfo.isWhite;
    // 游戏是否结束
    let over = false;
    let chessBoard = [];
    //初始化chessBord数组(表示棋盘的数组)
    for (let i = 0; i < 15; i++) {
        chessBoard[i] = [];
        for (let j = 0; j < 15; j++) {
            chessBoard[i][j] = 0;
        }
    }
    let chess = document.querySelector('#chess');
    let context = chess.getContext('2d');
    context.strokeStyle = "#BFBFBF";
    // 背景图片
    let logo = new Image();
    logo.src = "img/chessboard.jpg";
    logo.onload = function () {
        context.drawImage(logo, 0, 0, 450, 450);
        initChessBoard();
    }

    // 绘制棋盘网格
    function initChessBoard() {
        for (let i = 0; i < 15; i++) {
            context.moveTo(15 + i * 30, 15);
            context.lineTo(15 + i * 30, 430);
            context.stroke();
            context.moveTo(15, 15 + i * 30);
            context.lineTo(435, 15 + i * 30);
            context.stroke();
        }
    }

    // 绘制一个棋子, me 为 true
    function oneStep(i, j, isWhite) {
        context.beginPath();
        context.arc(15 + i * 30, 15 + j * 30, 13, 0, 2 * Math.PI);
        context.closePath();
        var gradient = context.createRadialGradient(15 + i * 30 + 2, 15 + j * 30 - 2, 13, 15 + i * 30 + 2, 15 + j * 30 - 2, 0);
        if (!isWhite) {
            gradient.addColorStop(0, "#0A0A0A");
            gradient.addColorStop(1, "#636766");
        } else {
            gradient.addColorStop(0, "#D1D1D1");
            gradient.addColorStop(1, "#F9F9F9");
        }
        context.fillStyle = gradient;
        context.fill();
    }

    chess.onclick = function (e) {
        if (over) {
            return;
        }
        if (!me) {
            return;
        }
        let x = e.offsetX;
        let y = e.offsetY;
        // 注意, 横坐标是列, 纵坐标是行
        let col = Math.floor(x / 30);
        let row = Math.floor(y / 30);
        if (chessBoard[row][col] == 0) {
            // TODO 发送坐标给服务器, 服务器要返回结果
            send(row, col);
            // oneStep(col, row, gameInfo.isWhite);
            // chessBoard[row][col] = 1;
        }
    }

    function send(row, col) {
        let req = {
            message: "putChess",
            userId: gameInfo.thisUserId,
            row: row,
            col: col
        };
        websocket.send(JSON.stringify(req));
    }
    
    // 在游戏就绪后，初始化完毕，就不再有游戏就绪响应了
    // 因此，修改 websocket.onmessage 方法，让这个方法里针对落子响应进行处理
    websocket.onmessage = function(e) {
        console.log("[handlerPutChess]" + e.data);
        let resp = JSON.parse(e.data);
        console.log(resp.status != 'putChess');
        if(resp.status != 'putChess') {
            console.log("响应类型错误！");
            return;
        }

        // 判定当前落子是自己的还是对方的
        let piecesInfo = resp.data;
        console.log(piecesInfo);
        
        if (piecesInfo.userId == gameInfo.thisUserId) {
            // 自己落子，根据自己的颜色，绘制一个棋子
            oneStep(piecesInfo.col, piecesInfo.row, gameInfo.isWhite);
        } else if (piecesInfo.userId == gameInfo.thatUserId) {
            // 对手落子
            oneStep(piecesInfo.col, piecesInfo.row, !gameInfo.isWhite);
        } else {
            // 响应错误
            console.log("[handlerPutChess] userId 错误！");
            return;
        }
        // 对应位置置为1
        chessBoard[piecesInfo.row][piecesInfo.col] = 1;
        // 交互双方落子轮次
        me = !me;
        setScreenText(me);

        // 判定游戏是否结束
        let screenDiv = document.querySelector('#screen');
        if(piecesInfo.winner != 0) {
            if (piecesInfo.winner == gameInfo.thisUserId) {
                // alert("你赢了！");
                screenDiv.innerHTML = "你赢了！";
            } else if (piecesInfo.winner == gameInfo.thatUserId) {
                // alert("很遗憾，你输了");
                screenDiv.innerHTML = "很遗憾，你输了";
            } else if(piecesInfo.winner == -1) {
                // alert("平局!");
            } else {
                alert("字段错误！" + piecesInfo.winner);
            }
            // 返回游戏大厅
            // location.replace("/game_hall.html");
            // 增加一个按钮，让玩家点击按钮后再返回到游戏大厅
            let backBtn = document.createElement('button');
            backBtn.innerHTML = '回到大厅';
            backBtn.onclick = function() {
                location.replace("/game_hall.html");
            }
            let fatherDiv = document.querySelector('.container>div');
            fatherDiv.appendChild(backBtn);
        }
    }
}


